package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.event.LoginRecordEvent;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.system.domain.CommonConfig;
import com.ruoyi.system.domain.SysLogininfor;
import com.ruoyi.system.domain.bo.CommonConfigBo;
import com.ruoyi.system.domain.vo.CommonConfigVo;
import com.ruoyi.system.domain.vo.LoginTimeConfigVo;
import com.ruoyi.system.mapper.CommonConfigMapper;
import com.ruoyi.system.service.ICommonConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 配置信息存储Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-30
 */
@RequiredArgsConstructor
@Service
public class CommonConfigServiceImpl implements ICommonConfigService {

    private final CommonConfigMapper baseMapper;

    /**
     * 记录登录信息
     */
    @Async
    @EventListener
    public void abnormalLoginRecord(LoginRecordEvent recordEvent) {
        HttpServletRequest request = recordEvent.getRequest();
        final UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        final String ip = ServletUtils.getClientIP(request);
        String address = AddressUtils.getRealAddressByIP(ip);
        StringBuilder s = new StringBuilder();
        s.append(getBlock(ip));
        s.append(address);
        s.append(getBlock(recordEvent.getUsername()));
        s.append(getBlock(recordEvent.getStatus()));
        s.append(getBlock(recordEvent.getMessage()));
        // 获取客户端操作系统
        String os = userAgent.getOs().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        // 封装对象
        SysLogininfor logininfor = new SysLogininfor();
        logininfor.setUserName(recordEvent.getUsername());
        logininfor.setIpaddr(ip);
        logininfor.setLoginLocation(address);
        logininfor.setBrowser(browser);
        logininfor.setOs(os);
        logininfor.setMsg(recordEvent.getMessage());
        // 日志状态
        if (StringUtils.equalsAny(recordEvent.getStatus(), Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
            logininfor.setStatus(Constants.SUCCESS);
        } else if (Constants.LOGIN_FAIL.equals(recordEvent.getStatus())) {
            logininfor.setStatus(Constants.FAIL);
        }
    }


    private String getBlock(Object msg) {
        if (msg == null) {
            msg = "";
        }
        return "[" + msg.toString() + "]";
    }


    /**
     * 查询配置信息存储
     */
    @Override
    public CommonConfigVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询配置信息存储列表
     */
    @Override
    public TableDataInfo<CommonConfigVo> queryPageList(CommonConfigBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<CommonConfig> lqw = buildQueryWrapper(bo);
        Page<CommonConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询配置信息存储列表
     */
    @Override
    public List<CommonConfigVo> queryList(CommonConfigBo bo) {
        LambdaQueryWrapper<CommonConfig> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<CommonConfig> buildQueryWrapper(CommonConfigBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<CommonConfig> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getType()), CommonConfig::getType, bo.getType());
        lqw.eq(bo.getCreateId() != null, CommonConfig::getCreateId, bo.getCreateId());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), CommonConfig::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增配置信息存储
     */
    @Override
    public Boolean insertByBo(CommonConfigBo bo) {
        CommonConfig add = BeanUtil.toBean(bo, CommonConfig.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改配置信息存储
     */
    @Override
    public Boolean updateByBo(CommonConfigBo bo) {
        CommonConfig update = BeanUtil.toBean(bo, CommonConfig.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CommonConfig entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除配置信息存储
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional
    public void saveConfigTypeInfo(CommonConfigBo bo) {
        // 根据类型来查询对应的配置信息
        String type = bo.getType();
        // 异常登录信息配置
        if ("login_time".equals(type)) {
            // 校验信息
            String info = bo.getInfo();
            if (!StringUtils.isNotBlank(info)) {
                throw new ServiceException("参数信息没有添加");
            }
            LoginTimeConfigVo configVo = JsonUtils.parseObject(info, LoginTimeConfigVo.class);
            if (configVo == null) {
                throw new ServiceException("参数信息没有添加");
            }
            List<String> weekList = configVo.getWeekConfig();
            if (weekList == null || weekList.isEmpty()) {
                throw new ServiceException("周期没有配置");
            }

            String startTime = configVo.getStartTime();
            String endTime = configVo.getEndTime();
            if (!StringUtils.isNotBlank(startTime)) {
                throw new ServiceException("开始时间没有配置");
            }
            if (!StringUtils.isNotBlank(endTime)) {
                throw new ServiceException("结束时间没有配置");
            }
            LambdaQueryWrapper<CommonConfig> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CommonConfig::getType, type);
            List<CommonConfig> commonConfigs = baseMapper.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(commonConfigs)) {
                // 更新信息
                CommonConfig commonConfig = commonConfigs.get(0);
                commonConfig.setInfo(bo.getInfo());
                baseMapper.updateById(commonConfig);
            } else {
                CommonConfig update = BeanUtil.toBean(bo, CommonConfig.class);
                baseMapper.insert(update);
            }
        } else if ("recover_time".equals(type)) {
            // 校验信息
            String info = bo.getInfo();
            if (!StringUtils.isNotBlank(info)) {
                throw new ServiceException("参数信息没有添加");
            }
            LoginTimeConfigVo configVo = JsonUtils.parseObject(info, LoginTimeConfigVo.class);
            if (configVo == null) {
                throw new ServiceException("参数信息没有添加");
            }
            List<String> weekList = configVo.getWeekConfig();
            if (weekList == null || weekList.isEmpty()) {
                throw new ServiceException("周期没有配置");
            }
            LambdaQueryWrapper<CommonConfig> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CommonConfig::getType, type);
            List<CommonConfig> commonConfigs = baseMapper.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(commonConfigs)) {
                // 更新信息
                CommonConfig commonConfig = commonConfigs.get(0);
                commonConfig.setInfo(bo.getInfo());
                baseMapper.updateById(commonConfig);
            } else {
                CommonConfig update = BeanUtil.toBean(bo, CommonConfig.class);
                baseMapper.insert(update);
            }
        }
    }
}
